package com.plant.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.plant.entity.RegisterCode;
import com.plant.entity.UgcDiviceToken;
import com.plant.entity.UgcFriends;
import com.plant.entity.UgcUser;
import com.plant.entity.UgcWeixinUserinf;
import com.plant.service.RegisterService;
import com.plant.tool.JavaSmsApi;
import com.plant.tool.Telrandom;

/**
 * @author JAVA工程师--李琦
 * 			---涉及的表：表1：
 * 			--secret 由 随机的字符串 和 密匙（token） 组成进行md5加密组成 pust_val 随机生成的字符串。可以是时间戳或乱码字符
 */
@Controller                             
@RequestMapping(value = "/register")       
public class RegisterAction {

    @Resource(name = "registerServiceImpl")  //spring 注入依赖管理 注入管理接口service
    private RegisterService registerService;
    
    
    @RequestMapping(value = "code") //--- 1..生成假的验证码
    @ResponseBody                                                   
    public Map<String,Object> user(HttpServletResponse response,String secret,String mdsc,String tel) {
    	response.setHeader("access-control-allow-origin","*");
    	Map<String,Object> map = new HashMap<String,Object>(); 
    	Md md=new Md();
    	String mds=md.md5calc(secret+"flower_duigu2016");
    	if(mdsc.endsWith(mds)){
    		if(tel==null){
    			map.put("error", "手机号不能为空");
    			map.put("state", 0);
        		return map;
    		}else{
        	SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        	String da=sim.format(new Date());
        	String dat=sim.format(new Date().getTime()+1000*60*1);
        	int x = (int)(Math.random()*9000+1000);
    		RegisterCode regcode=new RegisterCode();
    		regcode.setCreateTime(Timestamp.valueOf(da));//随机码创建时间
    		regcode.setEndTime(Timestamp.valueOf(dat));//随机码失效时间
    		regcode.setTel(tel);
    		regcode.setRandnomNum(x);
    		regcode.setState(0);
    		registerService.add(regcode);
    		map.put("randnomNum", x);
    		return map;
    		}
    	}else{
    		map.put("error", "秘钥错误");
    		map.put("state", 0);
    		return map;
    	}
    }
    
    
    
    @RequestMapping(value = "randomCode")//2.短信验证码
    @ResponseBody                                                   
    public Map<String,Object> RandomCode(HttpServletResponse response,String secret,String mdsc,String tel) {
    	response.setHeader("access-control-allow-origin","*");
    	Map<String,Object> map = new HashMap<String,Object>(); 
    	if(secret==null||mdsc==null){
    		map.put("message", "参数不能为空");
    		map.put("state", 0);
    		return map;
    	}else{
		    	Md md=new Md();
		    	String mds=md.md5calc(secret+"flower_duigu2016");
		    	if(mdsc.endsWith(mds)){
			    		if(tel==null){
			    			map.put("error", "手机号不能为空");
			    			return map;
			    		}else{
			    	        String apikey = "b8fe6db82ce852bda647575a9304765d ";
			    	        int x = (int)(Math.random()*9000+1000);//--生成4位随机数
			    	        String text ="【植物先生】您的验证码是"+x+"";
			    			SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			    			String da=sim.format(new Date());
			    			String dat=sim.format(new Date().getTime()+1000*60*1);
			    			RegisterCode regcode=new RegisterCode();
//			    			TestCode testcode=new TestCode();//----发送验证码  返回验证码
//			    			Integer x=testcode.test("cf_834430245", "19945116868ok", tel);
			    			try {
			    				JavaSmsApi.sendSms(apikey, text, tel);
							} catch (IOException e) {
								e.printStackTrace();
							}
			    			regcode.setCreateTime(Timestamp.valueOf(da));//随机码创建时间
			    			regcode.setEndTime(Timestamp.valueOf(dat));//随机码失效时间
			    			regcode.setTel(tel);
			    			regcode.setRandnomNum(x);
			    			regcode.setState(0);
			    			boolean b=registerService.add(regcode);
			    			if(b){
			    				map.put("state", 1);
			    				map.put("message", "生成验证码成功 请手机查看");
			    				return map;
			    			}else{
			    				map.put("state", 0);
			    				map.put("message", "生成验证码失败");
			    				return map;
			    			}
			    		  }
		    	}else{
		    		map.put("error", "秘钥错误");
		    		map.put("state", 0);
		    		return map;
		    }
    	}
 }
    
    
    
    @RequestMapping(value = "register")//---3.APP端用户注册
    @ResponseBody                                                   
    public Map<String,Object> Register(UgcDiviceToken ud,String divice_token,String tel,Integer code,String password,HttpServletResponse response,String time,String secret,String pust_val,RegisterCode rg,UgcUser user,HttpServletRequest request) {
    	response.setHeader("access-control-allow-origin","*");
    	Map<String,Object> map = new HashMap<String,Object>(); 
    	if(secret==null||pust_val==null||tel==null||code==null||password==null||divice_token==null){ //String tel,Integer code,String password,
    		map.put("message", "参数不能为空");
    		map.put("state", 0);
    		return map;
    	}else{
	    	Md md=new Md();
	    	String mds=md.md5calc(pust_val+"flower_duigu2016");
	    	if(secret.endsWith(mds)){
//    			String tel="18307211399";
//    			Integer code=6666;
//    			String password="mrplants";
    			rg.setTel(tel);
    			rg.setRandnomNum(code);
    			MDfive mdf=new MDfive();
    			String mdpassword=mdf.getmd5(mdf.getmd5(password));//----两次加密后用户登录密码
    			UgcUser u=new UgcUser();
    			u=registerService.checktel(rg);//----验证手机号 数据库是否存在
    			if(u!=null){//----如果手机号存在 提醒用户登录
    				map.put("message", "注册的用户手机号存在请直接登录");
    				map.put("state", 0);
    				return map;
    			}else{//----如果不存在 添加新用户 到用户表
	    				RegisterCode rgs=new RegisterCode();
	    				rgs=registerService.checkUser(rg);  //---判断手机验证码 是否正确
			    		if(rgs==null){
			    			map.put("message", "用户注册验证码错误");
			        		map.put("state", 0);
			        		return map;
			    		}else{
		    					registerService.update(rgs);//修改state
		    					SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    					String t=sim.format(new Date());
		    					GetIp getip=new GetIp();
		    					String ip=getip.getIp2(request);
		    					Telrandom te=new Telrandom();
		        				user.setTel(rg.getTel());
		        				int radomInt = new Random().nextInt(999999);//----随机产生6位数随机数
		        				user.setMyId("ID:"+radomInt);				//---注册用户编号
		        				user.setNickname("Mr."+te.test(rg.getTel()));//---注册用户姓名
		        				user.setPassword(mdpassword);				 //---注册用户密码
		        				user.setRegisterTime(Timestamp.valueOf(t));
		        				user.setIp(ip);
		        				user.setLevel("1");
		        				user.setCity("中国");
		        				user.setProvince("中国");
		        				user.setDiviceToken(divice_token);
		        				boolean b=registerService.addtel(user);
		        				if(b){
		        					ud.setCreateTime(Timestamp.valueOf(t));
		        					ud.setIp(ip);
		        					ud.setDiviceToken(divice_token);
		        					ud.setUserId(user.getId());
		        					boolean bb=registerService.AddDiviceToken(ud);
		        					if(bb){
		        						map.put("message", "添加Divice_token成功");
		        						map.put("state", 1);
		        					}else{
		        						map.put("message", "添加Divice_token失败");
		        						map.put("state", 0);
		        					}
		        					List<Object> list=new ArrayList<Object>();
		        					list=registerService.getBytel(rgs);
		        					UgcUser uu=null;
		        					for (int i = 0; i < list.size(); i++) {
										uu=(UgcUser) list.get(0);
									}
		        					int[] ids={149,150,151,152,153,154,35};
		        					for (int i = 0; i <ids.length; i++) {
		        						UgcFriends uf=new UgcFriends();
		        						uf.setReceiveUserId(uu.getId());
		        						uf.setApplyUserId(ids[i]);
		        						uf.setCreateTime(Timestamp.valueOf(t));
		        						uf.setIp(ip);
		        						registerService.addfriend(uf);
									}
		        					map.put("userinf", list);
		        					map.put("message","新用户注册成功");
		        					map.put("state", 1);
		        					return map;
		        				}else{
		        					map.put("message","网络不好注册失败");
		        					map.put("state", 0);
		        					return map;
		        				}
    				       }
    				 }
	    		}else{
	    		map.put("error", "秘钥错误");
	    		return map;
	    	}
    	}
    }
    
    @RequestMapping(value = "UpdatePass")//---4.APP端用户 修改密码
    @ResponseBody                                                   
    public Map<String,Object> UpdatePass(HttpServletResponse response,String time,String tel,Integer code,String password,String secret,String pust_val,RegisterCode rg,UgcUser user,HttpServletRequest request) {
    	response.setHeader("access-control-allow-origin","*");
    	Map<String,Object> map = new HashMap<String,Object>(); 
    	if(secret==null||pust_val==null||tel==null||code==null||password==null){
    		map.put("message", "参数秘钥+手机号+验证码+密码不能为空");
    		map.put("state", 0);
    		return map;
    	}else{
	    	Md md=new Md();
	    	String mds=md.md5calc(pust_val+"flower_duigu2016");
	    	if(secret.endsWith(mds)){
//					    	String tel="18307211399";
//					    	Integer code=6666;
//					    	String password="zhiwuxiansheng";
					    	rg.setTel(tel);
					    	rg.setRandnomNum(code);
					    	MDfive mdf=new MDfive();
					    	String mdpassword=mdf.getmd5(mdf.getmd5(password));//----两次加密后用户登录密码
					    	UgcUser u=new UgcUser();
					    	u=registerService.checktel(rg);//----验证手机号 数据库是否存在
					    	if(u==null){//----如果手机号存在 提醒用户登录
					    		map.put("message", "请先注册");
					    		map.put("state", 0);
					    		return map;
					    	}else{//----如果不存在 添加新用户 到用户表
					    		RegisterCode rgs=new RegisterCode();
					    		rgs=registerService.checkUser(rg);  //---判断手机验证码 是否正确
					    		if(rgs==null){
					    			map.put("message", "验证码错误");
					    			map.put("state", 0);
					    			return map;
					    		}else{
					    			registerService.update(rgs);//修改state
					    			List<Object> list1=new ArrayList<Object>();
					    			list1=registerService.getBytel(rgs);
					    			for (int i = 0; i < list1.size(); i++) {
										user=(UgcUser)list1.get(0);
									}
					    			user.setPassword(mdpassword);
					    			boolean b=registerService.UpdatePass(user);
					    			if(b){
					    				map.put("message","用户密码修改成功");
					    				map.put("state", 1);
					    				return map;
					    			}else{
					    				map.put("message","网络不好修改失败");
					    				map.put("state", 0);
					    				return map;
					    			}
					    		}
					    		
					    	}
	    	}else{
	    		map.put("error", "秘钥错误");
	    		return map;
	    	}
    	}
    }
    
    
    @RequestMapping(value = "PWlogin")//--5用户手机 密码登录验证
    @ResponseBody                                                   
    public Map<String,Object> Login(String divice_token,UgcDiviceToken ud,HttpServletResponse response,String secret,String pust_val,UgcUser user,HttpServletRequest request,String tel,String password) {
    	response.setHeader("access-control-allow-origin","*");
    	Map<String,Object> map = new HashMap<String,Object>(); 
    	if(secret==null||pust_val==null||tel==null||password==null||divice_token==null){
    		map.put("message", "参数为空");
    		map.put("state", 0);
    		return map;
    	}else{
	    	Md md=new Md();
	    	String mds=md.md5calc(pust_val+"flower_duigu2016");
	    	if(secret.endsWith(mds)){
	    		System.out.println(divice_token);
		    	user.setTel(tel);
		    	MDfive mdf=new MDfive();
		    	String mdpassword=mdf.getmd5(mdf.getmd5(password));//----两次加密后用户登录密码
		    	user.setPassword(mdpassword);
		    	UgcUser u=new UgcUser();
		    	RegisterCode rg=new RegisterCode();
		    	rg.setTel(tel);
		    	RegisterCode rgs=new RegisterCode();
		    	rgs.setTel(tel);
		    	u=registerService.checktel(rg);//----验证手机号 数据库是否存在
		    	if(u==null){//---如果不存在 提醒用户注册
			    		map.put("message", "用户不存在");
			    		map.put("state", 0);
			    		return map;
			    		}else{
			    		UgcUser uu=registerService.checkUser(user);
			    		if(uu==null){
			    			map.put("message","登录失败，检查密码是否正确");
			    			map.put("state", 0);
			    			return map;
			    		}else{
			    			if(uu.getDiviceToken()==null){
			    				uu.setDiviceToken(divice_token);
			    				registerService.UpdatePass(uu);
			    				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    					String t=sim.format(new Date());
		    					GetIp getip=new GetIp();
		    					String ip=getip.getIp2(request);
			    				ud.setCreateTime(Timestamp.valueOf(t));
	        					ud.setIp(ip);
	        					ud.setDiviceToken(divice_token);
	        					ud.setUserId(uu.getId());
	        					boolean bb=registerService.AddDiviceToken(ud);
	        					if(bb){
	        						map.put("message", "添加Divice_token成功");
	        						map.put("state", 1);
	        					}else{
	        						map.put("message", "添加Divice_token失败");
	        						map.put("state", 0);
	        					}
			    			}else if(uu.getDiviceToken().endsWith(divice_token)){
			    				System.out.println("用的是一样的手机");
			    			}else{
			    				uu.setDiviceToken(divice_token);
			    				registerService.UpdatePass(uu);
			    				map.put("message", "用户更换手机了");
			    			}
			    			List<Object> list=new ArrayList<Object>();
        					list=registerService.getBytel(rgs);
        					map.put("userinf", list);
			    			map.put("message","登录成功");
				    		map.put("state", 1);
				    		return map;
			    		}
		    	}
	    	}else{
	    		map.put("error", "秘钥错误");
	    		return map;
	    	}
    	}
    }
    
    
    
    @RequestMapping(value="wxlogin")//---6用户微信登录
    @ResponseBody
    public Map<Object,Object> identify(HttpServletRequest request,String headimgurl,String divice_token, UgcWeixinUserinf uwf,String sex,String nickname,UgcUser user,String openid,RegisterCode rg,String pust_val,String secret){
    	Map<Object,Object> map=new HashMap<Object, Object>();
    	if(secret==null||pust_val==null||openid==null){
    		map.put("message", "参数为空");
    		map.put("state", 0);
    		return map;	
    	}else{
		    	Md md=new Md();
		    	String mdc=md.md5calc(pust_val+"flower_duigu2016");//md5加密匹配
		    	if(secret.endsWith(mdc)){
    				   user.setWeixinOpenId(openid);
    				   UgcUser u=registerService.CheckOpenId(user);
		    		   if(u!=null){
		    			   	u.setDiviceToken(divice_token);
		    			   	registerService.UpdatePass(u);
		    			    List<Object> list=new ArrayList<Object>();
       					    list=registerService.GetByOpenId(user);
       					    map.put("userinf", list);
			    			map.put("message","登录成功");
				    		map.put("state", 1);
		    		   }else{
		    			   SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    			   String t=sim.format(new Date());
		    			   GetIp getip=new GetIp();
		    			   String ip=getip.getIp2(request);
		    			   uwf.setOpenId(openid);
		    			   registerService.AddWeiXinUser(uwf);
		    			   user.setNickname(nickname);
		    			   if(sex.endsWith("1")){
		    				   user.setSex("男");
		    			   }else{
		    				   user.setSex("女");
		    			   }
		    			   int radomInt = new Random().nextInt(999999);//----随机产生6位数随机数
	        			   user.setMyId("ID:"+radomInt);
		    			   user.setPhoto(headimgurl);
		    			   user.setDiviceToken(divice_token);
		    			   user.setWeixinOpenId(openid);
		    			   user.setRegisterTime(Timestamp.valueOf(t));
		    			   user.setIp(ip);
		    			   boolean b=registerService.addtel(user);
		    			   if(b){
		    				    List<Object> list=new ArrayList<Object>();
		    				    List<Object> list2=new ArrayList<Object>();
	        					list2=registerService.GetByOpenId(user);
	        					UgcUser uu=null;
	        					for (int i = 0; i < list2.size(); i++) {
									uu=(UgcUser) list2.get(0);
								}
	        					int[] ids={149,150,151,152,153,154,35};
	        					for (int i = 0; i <ids.length; i++) {
	        						UgcFriends uf=new UgcFriends();
	        						uf.setReceiveUserId(uu.getId());
	        						uf.setApplyUserId(ids[i]);
	        						uf.setCreateTime(Timestamp.valueOf(t));
	        						uf.setIp(ip);
	        						registerService.addfriend(uf);
								}
	       					   list=registerService.GetByOpenId(user);
	       					   map.put("userinf", list);
		    				   map.put("message", "登录成功");
		    				   map.put("state", 1);
		    			   }else{
		    				   map.put("message", "登录失败");
		    				   map.put("state", 0);
		    			   }
		    		   }
		    		   return map;
			    }else{
			    	map.put("message", "参数为空");
			    	map.put("state", 0);
			    	   return map;	
			}
    	}
    }
    
    
    
    
}
